import React, { Component } from 'react'
import { Radio } from 'antd'
import { TwsReactMarkdownPreview } from 'tws-antd'
import { getLangFromLocalStorage } from '../../constant/lang-util'

const RadioGroup = Radio.Group

export default class SingleChoice extends Component {
  changeAnswer (quiz, e) {
    const answer = e.target.value
    this.props.modifyAnswer(quiz, answer.toString())
  }

  getValue (quiz) {
    const preview = this.props.preview
    if (preview) {
      return parseInt(quiz.answer, 10)
    }
    if (quiz) {
      return parseInt(quiz.userAnswer, 10)
    }
    return -1
  }

  render () {
    const {isTutor, index, disabled, quiz} = this.props
    const status = quiz.answer || isTutor
    const lang = getLangFromLocalStorage()
    const description = quiz[`description_${lang}`] || quiz.description

    return <div className='mark-down-wrap'>
      <TwsReactMarkdownPreview source={`${index + 1}. ${description}`} />
      <div className='margin-t-1'>
        <RadioGroup
          onChange={this.changeAnswer.bind(this, quiz)}
          defaultValue={this.getValue(quiz)}
          disabled={!!status}>
          {quiz.choices.map((option, index) =>
            <Radio className='margin-l-4 radio-style'
              key={index}
              disabled={disabled}
              value={index}>
              {option[`choice_${lang}`] || option.choice}
            </Radio>)}
        </RadioGroup>
      </div>
    </div>
  }
}
